package com.nfit.seckilldemo1.service.impl;

import com.nfit.seckilldemo1.mapper.OrderMapper;
import com.nfit.seckilldemo1.mapper.StockMapper;
import com.nfit.seckilldemo1.pojo.Order;
import com.nfit.seckilldemo1.pojo.SeckillOrderMessage;
import com.nfit.seckilldemo1.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * ClassName:OrderServiceImpl
 * Package:com.nfit.seckilldemo1.service.impl
 * Description
 *
 * @Author L
 * @Create 2025/2/17 19:48
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 消费MQ消息，执行数据库操作
     * - 扣减库存（乐观锁）
     * - 创建订单
     * - 若失败则回滚Redis库存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createOrder(SeckillOrderMessage orderMessage) {
        // 1. 扣减数据库库存（注意此时Redis库存已预留）
        int updateRows = stockMapper.reduceStockWithVersion(
                orderMessage.getSkuId(),
                orderMessage.getQuantity(),
                0 // 从Redis操作后的版本号需要重新获取（此处示例简化为0）
        );
        if (updateRows <= 0) {
            throw new RuntimeException("库存扣减失败，可能存在并发问题");
        }

        // 2. 创建订单
        Order order = new Order();
        order.setUserId(orderMessage.getUserId());
        order.setSkuId(orderMessage.getSkuId());
        order.setQuantity(orderMessage.getQuantity());
        order.setStatus(0); // 初始状态为未支付
        order.setCreateTime(new Date());
        orderMapper.insert(order);

        // 3. 标记用户已购买（可选：也可在支付成功后标记）
        redisTemplate.opsForSet().add(
                "seckill:users:" + orderMessage.getSkuId(),
                orderMessage.getUserId().toString()
        );
    }
}

